<template>
	<el-form :model="account" ref="accountForm" :rules="rules" label-width="80px">
		<el-form-item label="名称" prop="username">
			<el-input v-model="account.username"></el-input>
		</el-form-item>
		<el-form-item label="密码" prop="password" v-show="type === FormType.ADD">
			<el-input v-model="account.password"></el-input>
		</el-form-item>
		<el-form-item label="昵称">
			<el-input v-model="account.nick"></el-input>
		</el-form-item>
		<el-form-item label="角色">
			<el-select placeholder="选择角色" v-model="account.r_id">
				<el-option v-for="item in roleList" :key="item.r_id" :label="item.rolename" :value="item.r_id"> </el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="头像" v-show="type === FormType.ADD">
			<!-- 
                auto-upload :是否自动上传图片
                list-type: 卡片样式
                show-file-list: 上传图片列表
            -->
			<el-upload
				name="headerimg"
				ref="uploadHeader"
				action="/"
				list-type="picture-card"
				:auto-upload="true"
				:show-file-list="false"
				:before-upload="bindBeforeUpload"
				:on-change="bindChangeFile"
			>
				<img v-if="imageUrl" :src="imageUrl" class="avatar-uploader" />
				<el-icon v-else><Plus /></el-icon>
			</el-upload>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="onAccountAddSubmit">确定</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts">
import { ref, type Ref, onMounted } from 'vue'
import type { IAccountAdd, IRole } from '@/utils/types'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { api } from '@/api/index'
import sha256 from 'js-sha256'
import { FormType } from '@/config/const'
import { filterImageUrl } from '@/utils'
const { RequestRegister, RequestRoleList, RequestMangerUpdate } = api
const roleList: Ref<Array<IRole>> = ref([])
const account: Ref<IAccountAdd> = ref({
	username: '',
	password: '',
	nick: '',
	r_id: ''
})
const rules = ref({
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})
let headerimgFile: File
const imageUrl = ref<string>('') //预览图片

const props = defineProps({
	modelValue: Boolean,
	type: String,
	currentAccount: Object
})
// const emit = defineEmits(['update:modelValue'])
const emit = defineEmits(['close'])

onMounted(() => {
	getRoleList()
	if (props.type === FormType.EDIT) {
		account.value = { ...account.value, ...props.currentAccount }
		imageUrl.value = filterImageUrl(account.value.headerimg as string)
	}
})
/**
 * 角色列表
 */
const getRoleList = async () => {
	const data = await RequestRoleList()
	const { resultCode, resultInfo } = data
	if (resultCode === 1) {
		roleList.value = resultInfo.roles
	}
}

/**
 * 添加账户
 */
const onAccountAddSubmit = () => {
	if (props.type === FormType.EDIT) {
		const {m_id, username, password, nick, r_id } = account.value
		// const formData = new FormData()
		// const psw = sha256(password)
		// formData.append('username', username)
		// formData.append('password', psw)
		// formData.append('nick', nick)
		// formData.append('roseid', r_id)
		// formData.append('headerimg', headerimgFile)

		RequestMangerUpdate({m_id, username, password, nick, role_id:r_id }).then(data => {
			const { resultCode, resultInfo } = data
			if (resultCode === 1) {
				ElMessage.success('编辑账户成功!')
				// emit('update:modelValue', false)
				emit('close')
			}
		})
	} else {
		const { username, password, nick, r_id } = account.value
		const formData = new FormData()
		const psw = sha256(password)
		formData.append('username', username)
		formData.append('password', psw)
		formData.append('nick', nick)
		formData.append('roseid', r_id)
		formData.append('headerimg', headerimgFile)

		RequestRegister(formData).then(data => {
			const { resultCode, resultInfo } = data
			if (resultCode === 1) {
				ElMessage.success('添加账户成功!')
				// emit('update:modelValue', false)
				emit('close')
			}
		})
	}
}

/**
 * 选择本地图片时触发
 * @param rawFile
 */
const bindChangeFile = (rawFile: any) => {
	// 方法一
	// const fileReader = new FileReader()
	// fileReader.addEventListener('load',(obj)=>{
	//     imageUrl.value = obj.currentTarget.result
	// })
	// fileReader.readAsDataURL(rawFile.raw)
	console.log('rawFile ', rawFile)
	headerimgFile = rawFile.raw
	const isOk = onPictureSizeAndType(rawFile.raw)
	// 方法二
	isOk && (imageUrl.value = URL.createObjectURL(rawFile.raw))
}

/**
 * 上传文件之前执行代码
 */
const bindBeforeUpload = (rawFile: File) => {
	console.log('bindBeforeUpload rawFile ', rawFile)
	return false
}

const onPictureSizeAndType = (rawFile: File) => {
	const typeArr = ['image/jpeg', 'image/png']
	if (!typeArr.includes(rawFile.type)) {
		ElMessage.error('图片必须是JPG格式或PNG格式!')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('图片大小不能超过2MB!')
		return false
	}
	return true
}
</script>

<style scoped>
.avatar-uploader {
	width: 158px;
	height: 158px;
	display: block;
}
</style>
